package com.power.sifa.correction.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.plf.common.domain.PageDataResponse;
import com.plf.core.base.model.Ha_attachment;
import com.plf.core.base.model.Ha_depart;
import com.plf.core.base.service.Ha_attachmentService;
import com.plf.core.base.service.Ha_departService;
import com.plf.core.common.service.BaseServiceImpl;
import com.power.sifa.aop.service.SMService;
import com.power.sifa.correction.dao.Apl_condeploy_personDao;
import com.power.sifa.correction.model.Apl_condeploy_person;
import com.power.sifa.correction.model.Crc_person;
import com.power.sifa.correction.model.pageInfo.Apl_condeploy_personPageInfo;
import com.power.sifa.correction.service.Apl_condeploy_personService;
import com.power.sifa.correction.service.Crc_personService;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 社区矫正人员布控人员信息业务层实现
 */
@Service
public class Apl_condeploy_personServiceImpl extends BaseServiceImpl implements Apl_condeploy_personService {

    @Resource
    private Apl_condeploy_personDao dao;
    @Resource
    private Crc_personService crc_personService;
    @Resource
    private Ha_departService ha_departService;
    @Resource
    private SMService smService;
    @Resource
    private Ha_attachmentService ha_attachmentService;

    @Override
    public Apl_condeploy_person getById(Serializable id) {
        return dao.findById(id).orElse(null);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveOrUpdate(Apl_condeploy_person apl_condeploy_person) {
        // save 如果数据库不存在这条数据，就会执行保存（即将这条数据插入到数据库）；如果数据库存在这条数据，就会根据主键去更新这条数据
        if (apl_condeploy_person.getPrimaryKey() != null) {
            Apl_condeploy_person apl_condeploy_personfDb = dao.findById(apl_condeploy_person.getPrimaryKey()).orElse(null);
            if (apl_condeploy_personfDb != null) {
                BeanUtils.copyProperties(apl_condeploy_person, apl_condeploy_personfDb);
                dao.save(apl_condeploy_personfDb);
                return;
            }
        }
        dao.save(apl_condeploy_person);
    }

    @Override
    public void removeById(Serializable id) {
        dao.deleteById(id);
    }

    @Override
    public Page<Apl_condeploy_person> findAll(Apl_condeploy_personPageInfo pageInfo) {
        //排序等定义
        Sort sort;
        if ("asc".equals(pageInfo.getOrder())) {
            sort = Sort.by(Sort.Direction.ASC, pageInfo.getSort());
        } else {
            sort = Sort.by(Sort.Direction.DESC, pageInfo.getSort());
        }
        //分页的定义
        Pageable pageable = PageRequest.of(pageInfo.getPageNumber() <= 1 ? 0 : pageInfo.getPageNumber() - 1, pageInfo.getPageSize(), sort);
        //查询条件
        Specification spec = this.createSpecification(pageInfo);
        return dao.findAll(spec, pageable);
    }

    @Transactional(rollbackFor = Exception.class)
    public void removeByIds(List<Integer> ids) {
        dao.removeByIds(ids);
    }

    @Override
    public List<Apl_condeploy_person> findAll() {
        return dao.findAll();
    }

    @Override
    public void saveAll(List<Apl_condeploy_person> list) {
        dao.saveAll(list);
    }


    @Override
    public Apl_condeploy_person findCondeployInfo(String id, String applyid) {
        Crc_person personObj = this.crc_personService.getById(id);
        Apl_condeploy_person cPerson = JSON.parseObject(JSON.toJSONString(personObj), Apl_condeploy_person.class);
        try {
            cPerson.setCardno(smService.decrypt(personObj.getCardno()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        cPerson.setConcode(personObj.getId());
        cPerson.setId(applyid);
        if (ObjectUtil.isNotNull(personObj.getDeptid())) {
            Ha_depart departObj = this.ha_departService.getById(personObj.getDeptid());
            cPerson.setExeaddr(departObj.getName());
        }
        cPerson.setPenalty(personObj.getPerform());
        queryAvatarUrl(Collections.singletonList(cPerson));
        return cPerson;
    }

    @Override
    public PageDataResponse findList(Apl_condeploy_personPageInfo pageinfo) {
        List<Apl_condeploy_person> list = this.dao.findList(pageinfo);
        queryAvatarUrl(list);
        // 分页
        PageDataResponse page = new PageDataResponse();
        if (CollectionUtil.isNotEmpty(list)) {
            for (Apl_condeploy_person person : list) {
                try {
                    person.setCardno(smService.encrypt(person.getCardno()));
                    person.setPhone(smService.encrypt(person.getPhone()));
                    person.setName(smService.encrypt(person.getName()));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            Long total = Long.valueOf(pageinfo.getAllcount());
            int size = pageinfo.getPageSize() * pageinfo.getPageNumber();
            if (total.intValue() - size > 0) {
                page.setNextPage(pageinfo.getPageNumber() + 1);
            }
            page.setSize(pageinfo.getPageSize());
            page.setCurrent(pageinfo.getPageNumber());
            page.setTotal(total);
        } else {
            page.setSize(0);
            page.setCurrent(1);
            page.setTotal(0L);
        }
        page.setRecords(list);
        return page;
    }


    /**
     * 查询头像图片的url地址
     *
     * @param personList
     */
    private void queryAvatarUrl(List<Apl_condeploy_person> personList) {
        if (CollectionUtil.isNotEmpty(personList)) {
            // 拿取对应的id
            List<String> attachmentIds = personList.stream().filter(element -> ObjectUtil.isNotNull(element) && ObjectUtil.isNotNull(element.getAvatar())).map(Apl_condeploy_person::getAvatar).collect(Collectors.toList());
            Map<String, Ha_attachment> ha_attachmentMap = ha_attachmentService.getHa_attachmentsByIds(attachmentIds);
            if (ObjectUtil.isNotNull(ha_attachmentMap)) {
                personList.stream().forEach(m -> {
                    Optional.ofNullable(ha_attachmentMap.get(m.getAvatar())).ifPresent(then -> m.setAvatarUrl(ha_attachmentMap.get(m.getAvatar()).getPath()));
                });
            }
        }
    }

}
